package controllers

import (
	"cat_mouse/core/dao"
	m "cat_mouse/core/model"
	"cat_mouse/core/service"
	"cat_mouse/infra/common"
	"cat_mouse/infra/response"
	ossSvc "cat_mouse/infra/service/oss"
	"cat_mouse/infra/utils"
	jwtToken "cat_mouse/infra/utils/jwt_token"
	"cat_mouse/infra/utils/log"
	"cat_mouse/infra/utils/redis"
	"github.com/gin-gonic/gin"
	"time"
)

type UserController struct {
	userService service.IUserService
}

func UserControllerRegister(router *gin.RouterGroup) {
	userController := UserController{
		service.NewUserService(),
	}
	router.POST("login", userController.Login)
	router.POST("refreshToken", userController.RefreshToken)
	router.GET("info", userController.UserInfo)
	router.PUT("info", userController.UpdateInfo)
	router.GET("", userController.ListUsers)
	router.GET("uploadToken", userController.ImageUploadToken)
}

// Login 用户登录
func (u *UserController) Login(c *gin.Context) {
	// todo 补充登录功能
}

// UserInfo 获取用户信息
func (u *UserController) UserInfo(c *gin.Context) {

}

// RefreshToken 刷新token
func (u *UserController) RefreshToken(c *gin.Context) {
	var (
		token string
		err   error
	)
	userInfo := utils.MustGetUser(c)
	if token, err = jwtToken.GenerateToken(jwtToken.AuthCodeInfo{
		UserId:   userInfo.UserId,
		UserName: userInfo.Username,
	}, time.Duration(utils.GetSysCfg().TokenExpire)*time.Second); err != nil {
		log.Logger.Error(err)
		response.InternalError(c, err.Error())
		return
	}
	utils.SafeGo(func() {
		_ = dao.NewTokenDao().Create(&m.Token{
			UserId: userInfo.UserId,
			Token:  token,
			ExpireAt: common.JSONTime{
				Time: time.Now().Add(time.Duration(utils.GetSysCfg().TokenExpire) * time.Second),
			},
		})
	})
	_ = redis.Set(token, userInfo.UserId, utils.GetSysCfg().TokenExpire)
	_, _ = redis.Delete(c.GetHeader("token"))
	response.OK(c, map[string]interface{}{"token": token, "user": userInfo})
}

func (u *UserController) UpdateInfo(c *gin.Context) {

}

func (u *UserController) ListUsers(c *gin.Context) {

}

func (u *UserController) ImageUploadToken(c *gin.Context) {
	resp, err := ossSvc.GetALiYunClient().GetUploadCredential()
	if err != nil {
		log.Logger.Error(err)
		response.InternalError(c, err.Error())
		return
	}
	timeExpire, timeErr := time.Parse(time.RFC3339, resp.Credentials.Expiration)
	if timeErr != nil {
		log.Logger.Error(timeErr)
		response.InternalError(c, timeErr.Error())
		return
	}
	c.JSON(200, map[string]string{
		"AccessKeyId":     resp.Credentials.AccessKeyId,
		"AccessKeySecret": resp.Credentials.AccessKeySecret,
		"SecurityToken":   resp.Credentials.SecurityToken,
		"Expiration":      timeExpire.Format(common.TimeLayout),
	})
}
